package com.whisperly.echotalk.starryb.schemas;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;
import com.whisperly.echotalk.bean.ApiResponse;
import com.whisperly.echotalk.bean.VersionCheckRequest;
import com.whisperly.echotalk.bean.VersionCheckResponse;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.ApiClient;
import com.whisperly.echotalk.starryb.netWorkUtils.ApiService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VersionUpgrade extends AppCompatActivity {
    private static final String TAG = "VersionUpgrade";

    private TextView versionTextView;
    private TextView currentVersionTextView;
    private TextView updateDescriptionTextView;
    private TextView updateContentTextView;
    private Button checkUpdateButton;
    private View updateInfoLayout;
    private View loadingLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.version_upgrade_act);

        initViews();
        displayCurrentVersion();

        // 自动检查更新
        checkForUpdates();


    }

    private void initViews() {
        versionTextView = findViewById(R.id.versionTextView);
        currentVersionTextView = findViewById(R.id.currentVersionTextView);
        updateDescriptionTextView = findViewById(R.id.updateDescriptionTextView);
        updateContentTextView = findViewById(R.id.updateContentTextView);
        checkUpdateButton = findViewById(R.id.checkUpdateButton);
        updateInfoLayout = findViewById(R.id.updateInfoLayout);
        loadingLayout = findViewById(R.id.loadingLayout);

        // 设置按钮点击事件
        checkUpdateButton.setOnClickListener(v -> checkForUpdates());
    }

    @SuppressLint("SetTextI18n")
    private void displayCurrentVersion() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pInfo = pm.getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            int versionCode = pInfo.versionCode;

            if (currentVersionTextView != null) {
                currentVersionTextView.setText(getString(R.string.now_app) + version + " (" + versionCode + ")");
                currentVersionTextView.setVisibility(View.VISIBLE);
            }

            // 兼容原有的versionTextView
            if (versionTextView != null) {
                versionTextView.setText(getString(R.string.now_version, version));
                versionTextView.setVisibility(View.VISIBLE);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "获取版本信息失败", e);
        }
    }

    /**
     * 检查更新
     */
    private void checkForUpdates() {
        showLoading(true);

        try {
            PackageManager pm = getPackageManager();
            PackageInfo pInfo = pm.getPackageInfo(getPackageName(), 0);

            VersionCheckRequest request = new VersionCheckRequest();
            request.setPlatform("android");
            request.setCurrentVersion(pInfo.versionName);
            request.setCurrentVersionCode(pInfo.getLongVersionCode());
            request.setPackageName(getPackageName());

            Log.d(TAG, "检查更新请求: " + request.toString());

            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            Call<ApiResponse<VersionCheckResponse>> call = apiService.checkVersion(request);

            call.enqueue(new Callback<ApiResponse<VersionCheckResponse>>() {
                @Override
                public void onResponse(Call<ApiResponse<VersionCheckResponse>> call,
                                       Response<ApiResponse<VersionCheckResponse>> response) {
                    runOnUiThread(() -> {
                        showLoading(false);

                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse<VersionCheckResponse> apiResponse = response.body();
                            if ("200".equals(apiResponse.getCode())) {
                                handleUpdateResponse(apiResponse.getData());
                            } else {
                                showError(getString(R.string.now_fail) + apiResponse.getMsg());
                            }
                        } else {
                            showError(getString(R.string.now_server_fail));
                        }
                    });
                }

                @Override
                public void onFailure(Call<ApiResponse<VersionCheckResponse>> call, Throwable t) {
                    runOnUiThread(() -> {
                        showLoading(false);
                        showError(getString(R.string.now_network_fail) + t.getMessage());
                    });
                }
            });

        } catch (PackageManager.NameNotFoundException e) {
            showLoading(false);
            showError(getString(R.string.now_get_fail));
        }
    }

    /**
     * 处理更新响应
     */
    private void handleUpdateResponse(VersionCheckResponse response) {
        Log.d(TAG, "更新检查结果: " + response.toString());

        if (response.getHasUpdate() != null && response.getHasUpdate()) {
            showUpdateAvailable(response);
        } else {
            showNoUpdateAvailable();
        }
    }

    /**
     * 显示有更新可用
     */
    @SuppressLint("SetTextI18n")
    private void showUpdateAvailable(VersionCheckResponse response) {
        updateInfoLayout.setVisibility(View.VISIBLE);

        // 显示版本信息
        if (updateDescriptionTextView != null) {
            String versionInfo = getString(R.string.now_app_version) + response.getLatestVersion() +
                    getString(R.string.now_app_version_new) + VersionManager.getCurrentVersionName(this);
            updateDescriptionTextView.setText(versionInfo);
            updateDescriptionTextView.setVisibility(View.VISIBLE);
        }

        // 显示更新内容
        if (updateContentTextView != null && response.getUpdateContent() != null) {
            updateContentTextView.setText(getString(R.string.now_content) + response.getUpdateContent());
            updateContentTextView.setVisibility(View.VISIBLE);
        }

        Toaster.show(getString(R.string.now_find) + response.getLatestVersion() + getString(R.string.now_play_update));
    }

    /**
     * 显示没有更新
     */
    private void showNoUpdateAvailable() {
        updateInfoLayout.setVisibility(View.VISIBLE);

        if (updateDescriptionTextView != null) {
            updateDescriptionTextView.setText(R.string.now_is_new);
            updateDescriptionTextView.setVisibility(View.VISIBLE);
        }

        if (updateContentTextView != null) {
            updateContentTextView.setText(R.string.now_tips);
            updateContentTextView.setVisibility(View.VISIBLE);
        }

        // 修改检查更新按钮文本
        checkUpdateButton.setText(R.string.now_re);
        checkUpdateButton.setVisibility(View.VISIBLE);

        Toaster.show(getString(R.string.now_is_check));
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean show) {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(show ? View.VISIBLE : View.GONE);
        }

        if (updateInfoLayout != null) {
            updateInfoLayout.setVisibility(show ? View.GONE : View.VISIBLE);
        }

        checkUpdateButton.setEnabled(!show);
        checkUpdateButton.setText(show ? getString(R.string.now_checking) : getString(R.string.now_checked));
    }

    /**
     * 显示错误信息
     */
    @SuppressLint("SetTextI18n")
    private void showError(String error) {
        Log.e(TAG, error);
        Toaster.show(error);

        // 显示错误状态
        if (updateDescriptionTextView != null) {
            updateDescriptionTextView.setText("❌ " + error);
            updateDescriptionTextView.setVisibility(View.VISIBLE);
        }

        updateInfoLayout.setVisibility(View.VISIBLE);
    }
}